<?php

	/*
	 * All rights Reserved, Designed By www.youyacao.com <br>
	 * @Description:key <br>
	 * @version 蜻蜓C影视追剧系统  <br>
	 * @author:成都市一颗优雅草科技有限公司  <br>
	 * 注意：使用我司开源源代码请遵循license文件的协议仅供个人非盈利使用，禁止用于其他的商业用途
	 * 需要商业用途或者定制开发等可访问songshu.youyacao.com  联系QQ:2853810243 422108995 23625059584
	 * 正版系统查询系统 zhengbancha.youyacao.com
	 */


namespace App\Admin\Actions;

use App\Models\Device;
use App\Services\LotService;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;


class KeySW extends RowAction
{
    protected $model;

//    protected $keysw;//开关状态
    /**
     * @return string
     */
    protected $title = '按键开关';

    public function __construct(string $model = null, $key_sw = 1)
    {
        if ($key_sw) {
            $this->title = '关闭按键';
        } else {
            $this->title = '开启按键';
        }
//        dd($key_sw);
//        $this->keysw=$key_sw;
        $this->model = $model;
    }

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $DeviceName = $request->get('DeviceName');
        $key_sw = $request->get('key_sw');
        $model = Device::find($this->getKey());
        $dev = new LotService();
        $key_sw ? $sw = 'DISABLE' : $sw = 'ENABLE';
        $msgarray = [
            'KEY' => $sw
        ];
        $list = $dev->Pub($DeviceName, $msgarray);
        if (isset($list['Success']) && $list['Success']) {
//            return $this->response()->success('执行成功')->refresh();
//            $model->devstatus=1;
            $model->key_sw = !$key_sw;
            $res = $model->save();
            if ($res) {
                return $this->response()->alert(true)->success('执行成功')->detail(json_encode($list))->refresh();
            } else {
                return $this->response()->alert(true)->error('执行失败')->detail(json_encode($list))->refresh();
            }
        } else {
            return $this->response()->alert(true)->error('执行失败')->detail(json_encode($list))->refresh();
        }
    }

    /**
     * @return string|array|void
     */
    public function confirm()
    {
        return ['确认操作?', '开启电源'];
    }

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [
            // 发送当前行 username 字段数据到接口
            'DeviceName' => $this->row->DeviceName,
            'key_sw' => $this->row->key_sw,
        ];
    }
}
